# -*- coding: utf-8 -*-
import datetime
import sys
from time import sleep
import re
# from sql_ac.sql_1 import insert_merberid, select_all, update_merberid
import pynput
from selenium import webdriver
from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# chrome_options 初始化选项
sys.setrecursionlimit(1000000)
# chrome_options 初始化选项
chrome_options = webdriver.ChromeOptions()
# 设置浏览器初始 位置x,y & 宽高x,y
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument(f'--window-position={217},{92}')
chrome_options.add_argument(f'--window-size={1222},{816}')
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
chrome_options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
chrome_options.add_argument('–headless')
desired_capabilities = DesiredCapabilities.CHROME  # 修改页面加载策略
desired_capabilities["pageLoadStrategy"] = "none"
driver = webdriver.Chrome(options=chrome_options)
# with open('stealth.min.js') as f:
#     js = f.read()
# driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
#   "source": js
# })
driver.set_page_load_timeout(20)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
})
wait = WebDriverWait(driver, 20)


def main():
    try:
        driver.get('http://cdxjj.chengdu.gov.cn/xjjfzw/c001003/2021-08/27/content_ccda8c992aa2433093abd0912d8a0833.shtml')
        print(driver.find_element_by_xpath('//*').text)
        input('123')
    except:
        input('123')
        driver.execute_script('window.stop()')
    for i in select_all('merberid')[2489:]:
        print(i[1])
        driver.find_element_by_xpath('//input[@id="home-header-searchbox"]').clear()
        driver.find_element_by_xpath('//input[@id="home-header-searchbox"]').send_keys(i[1])
        q = driver.find_elements_by_xpath('//button[@class="single"]')[0]
        ye1 = driver.current_window_handle
        driver.execute_script("arguments[0].click();", q)
        all_h = driver.window_handles
        driver.switch_to.window(all_h[1])
        d = driver.current_url
        d = re.findall(r"keywords=(.+?)&n=", d)[0]
        update_merberid(d, i[1])
        driver.close()
        driver.switch_to.window(ye1)


if __name__ == '__main__':
    main()

# 查找keyword 吗
